package cn.yanghan.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 拦截器转发token
 */
@Component
@Slf4j
public class TokenInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        //获取请求对象,强转成它的子类
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        //获取请求
        HttpServletRequest request = requestAttributes.getRequest();
        //获取请求头(token)，得到一个对象
        String authorization = request.getHeader("Authorization");
        //把token设置到fengin的请求头
        requestTemplate.header("Authorization",authorization);
        log.info("拦截器转发Token {}",authorization);
    }
}
